<!-- 自定义上传口播文本创建任务 -->
<template>
  <div class="min-h-screen  text-white py-8">
    <div class="mx-auto px-6">
      <!-- 步骤进度条 -->
      <div class="mb-12">
        <div class="flex justify-between items-center relative">
          <div class="absolute left-[5%] right-[5%] top-[35%] h-0.5 bg-gray-700 "></div>
          <div class="absolute left-[5%] right-[5%] top-[35%] h-0.5 ">
            <div class="h-full bg-green-500 transition-all duration-300" :style="`width: ${(currentStep / (steps.length - 1)) * 100}%`"></div>
          </div>
          <div v-for="(step, index) in steps" :key="index"
               class="flex flex-col items-center relative z-10">
            <div :class="`w-10 h-10 rounded-full flex items-center justify-center mb-2 border-2 transition-all duration-300
${currentStep > index ? 'bg-green-500 border-green-500' : currentStep === index ? 'bg-[#2468F2] border-[#2468F2]' : 'bg-gray-700 border-gray-700'}`">
              <i v-if="currentStep > index" class="fas fa-check"></i>
              <span v-else>{{ index + 1 }}</span>
            </div>
            <span class="text-sm transition-colors duration-300" :class="currentStep === index ? 'text-white' : 'text-gray-400'">
{{ step }}
</span>
          </div>
        </div>
      </div>
      <!-- 表单内容区 -->
      <div class="bg-gray-800 rounded-lg p-8 mb-8">
        <!-- 第五步：发布配置 -->
        <div v-if="currentStep === 3">
          <t-space style="margin-bottom: 10px;"  size="24px">
<!--            <t-checkbox v-model="isAutoFb"> 自动剪辑发布 </t-checkbox>-->
            <t-checkbox  v-model="isAutoJjjb"> 包装剪辑 </t-checkbox>
            <t-checkbox  v-model="isAutoFbjb"> 发布 </t-checkbox>
          </t-space>
          <div v-if="isAutoJjjb || isAutoFbjb">
          <t-card v-for="(item,key) in schedule" v-bind:key="key" style="margin-bottom: 20px">

            <div class="flex justify-between items-center">
              <div style="width: 100%; margin-right: 20px;">
              <t-row :gutter="{ xs: 8, sm: 16, md: 24, lg: 32, xl: 32, xxl: 40 }" >
                <t-col :span="12">
                  <t-form-item label="选择设备" >
                    <t-tree-select
                        filterable
                        :data="devices"
                        v-model="item.target_device"
                        multiple
                        placeholder="请选择"
                    >
<!--                      <t-option v-for="(device, index) in devices" :key="index" :value="device.id" :label="device.device_name">-->
<!--                        {{ device.device_name }}({{ device.device_bname }})-->
<!--                      </t-option>-->
                    </t-tree-select>
                  </t-form-item>
                </t-col>
                <t-col :span="6"  v-if="isAutoFbjb">
                  <t-form-item label="发布类型" >
                    <t-select
                        v-model="item.schedule_type"
                        :options="schedule_types"
                        placeholder="请选择"
                    />
                  </t-form-item>
                </t-col>
                <t-col :span="6" v-if="isAutoFbjb">
                  <t-form-item label="发布平台" >
                    <t-select
                        v-model="item.platform"
                        :options="platforms"
                        multiple
                        placeholder="请选择"
                    />
                  </t-form-item>
                </t-col>
              </t-row>
              <t-card  v-if="item.schedule_type===1 && isAutoFbjb">
                 <t-row :gutter="{ xs: 8, sm: 16, md: 24, lg: 32, xl: 32, xxl: 40 }" >
                <t-col :span="12" >
                  <t-row :gutter="16"  v-for="(time,t) in item.schedule_time" v-bind:key="t">
                    <t-col :span="6" >
                      <t-form-item label="发布时间" labelAlign="left" labelWidth="100">
                        <t-time-range-picker clearable  v-model="item.schedule_time[t].time" style="width: 100%"></t-time-range-picker>
                      </t-form-item>
                    </t-col>
                    <t-col :span="5" >
                      <t-form-item label="发布数量" labelAlign="left" labelWidth="100">
                        <t-input v-model="item.schedule_time[t].push_num" style="width: 100%" ></t-input>
                      </t-form-item>
                    </t-col>
                    <t-col :span="1" style="padding-right: 20px" v-if="t>0" >
                      <t-button theme="danger" @click="removeTime(key,t)" >
                        <template #icon><DeleteIcon /></template>
                      </t-button>
                    </t-col>
                  </t-row>
                  <t-row :gutter="{ xs: 8, sm: 16, md: 24, lg: 32, xl: 32, xxl: 40 }"   >
                    <t-col :span="12" style="text-align: center" >
                      <t-button theme="primary" @click="addTime(key)">
                        <template #icon><add-icon />新增时间</template>
                      </t-button>
                    </t-col>
                  </t-row>
                </t-col>

              </t-row>
              </t-card>
              <t-row :gutter="{ xs: 8, sm: 16, md: 24, lg: 32, xl: 32, xxl: 40 }"  v-if="item.schedule_type===2 && isAutoFbjb">
                <t-col :span="6" v-if="item.schedule_type===2">
                  <t-form-item label="间隔时长(小时)" >
                    <t-input-number v-model="item.schedule_value" :max="24" :min="1" :step="1" :decimal-places="0"  />
<!--                    <t-input v-model="item.schedule_value" type="number"></t-input>-->
                  </t-form-item>
                </t-col>
                <t-col :span="6">
                  <t-form-item label="发布数量" >
                    <t-input v-model="item.push_num" type="number"></t-input>
                  </t-form-item>
                </t-col>
              </t-row>
              </div>
              <div>

                <t-button theme="danger" @click="removeSchedule(key)" v-if="key>0">
                  <template #icon><DeleteIcon /></template>
                </t-button>
              </div>
            </div>



          </t-card>
<!--          <t-row :gutter="{ xs: 8, sm: 16, md: 24, lg: 32, xl: 32, xxl: 40 }" style="margin-top: 20px">-->
<!--            <t-col :span="12" style="text-align: center">-->
<!--              <t-button theme="primary" @click="addSchedule" >-->
<!--                <template #icon><add-icon />新建配置</template>-->
<!--              </t-button>-->
<!--            </t-col>-->
<!--          </t-row>-->
          </div>

        </div>
        <div v-if="currentStep === 0">
          <div class="mb-6">
            <label class="block mb-2">任务名称</label>
            <input v-model="formData.taskName"
                   class="w-full bg-gray-700 rounded-lg px-4 py-2 border-none text-white"
                   :class="{'border-red-500': errors.taskName}"
                   placeholder="请输入任务名称"/>
            <span v-if="errors.taskName" class="text-red-500 text-sm mt-1">{{ errors.taskName }}</span>
          </div>
          <div class="mb-6">
            <label class="block mb-2">上传口播文本表格文件</label>
            <t-upload
                v-model="files"
                accept=".xlsx"
                action="http://dev.blueant.pro/base/api.upload/file"
                :abridge-name="[8, 6]"
                theme="file-input"
                placeholder="请选择需要上传的Excel文件"
                @success="handleSuccess"
                @fail="handleFail"
            ></t-upload>
            <t-link theme="primary"  href="http://dev.blueant.pro/ziyuan/自定义口播文本模板.xlsx" target="_blank" style="margin-top: 10px">
              <template #prefix-icon>
                <link-icon />
              </template>
              点击下载表格文件模板
            </t-link>
            <p v-if="parseExcelResulet.errors" class="text-red-500 text-sm mt-1">{{ parseExcelResulet.errors }}</p>
            <p v-if="parseExcelResulet.success"  class="text-sm mt-1">{{ parseExcelResulet.success }}</p>
          </div>



        </div>
        <!-- 第二步：AI改写设置 -->


        <!-- 第三步：音频配置 -->
        <div v-if="currentStep === 1">
          <div class="mb-6">
            <label class="block mb-2">清晰度选择</label>
            <div class="relative">
              <t-select
                  v-model="formData.selectedAudioPlatform"
                  :options="audioPlatforms"
                  placeholder="请选择"
                  @change="selectAudioPlatform"
              />
              <span v-if="errors.selectedAudioPlatform" class="text-red-500 text-sm mt-1">{{ errors.selectedAudioPlatform }}</span>
            </div>
          </div>
          <div class="mb-6">
            <label class="block mb-2">声音选择</label>
            <div class="relative">
              <t-select
                  v-model="formData.selectedVoice"
                  :options="platformVoices"
                  placeholder="请选择"

              />
              <span v-if="errors.selectedVoice" class="text-red-500 text-sm mt-1">{{ errors.selectedVoice }}</span>
            </div>
          </div>
          <div class="mb-6" v-if="platformVoicesModel.length>0">
            <label class="block mb-2">模型选择</label>
            <div class="relative">
              <t-select
                  v-model="formData.selectedVoiceModel"
                  :options="platformVoicesModel"
                  placeholder="请选择"

              />
              <span v-if="errors.selectedVoiceModel" class="text-red-500 text-sm mt-1">{{ errors.selectedVoiceModel }}</span>
            </div>
          </div>



        </div>
        <!-- 第四步：视频配置 -->
        <div v-if="currentStep === 2">
          <div class="mb-6">
            <label class="block mb-2">清晰度选择</label>
            <div class="relative">

              <t-select
                  v-model="formData.selectedVideoPlatform"
                  :options="videoPlatforms"
                  placeholder="请选择"
                  @change="selectVideoPlatform"
              />
              <span v-if="errors.selectedVideoPlatform" class="text-red-500 text-sm mt-1">{{ errors.selectedVideoPlatform }}</span>
            </div>
          </div>
          <div>
            <label class="block mb-2">视频模板</label>
            <div class="relative">

              <t-select
                  v-model="formData.selectedVideo"
                  :options="platformVideos"
                  placeholder="请选择"
              />
              <span v-if="errors.selectedVideo" class="text-red-500 text-sm mt-1">{{ errors.selectedVideo }}</span>
            </div>
          </div>
        </div>
        <!-- 第五步：其他配置 -->
<!--        <div v-if="currentStep === 4">-->
<!--          <div class="mb-6">-->
<!--            <label class="block mb-2">其他设置</label>-->
<!--            <textarea v-model="formData.otherConfig"-->
<!--                      class="w-full bg-gray-700 rounded-lg px-4 py-2 border-none text-white h-32"-->
<!--                      placeholder="请输入其他配置"></textarea>-->
<!--          </div>-->
<!--        </div>-->
      </div>
      <!-- 底部操作栏 -->
      <div class="flex justify-between">
        <button @click="cancel"
                class="px-6 py-2 bg-gray-700 rounded-lg hover:bg-gray-600 !rounded-button whitespace-nowrap">
          取消
        </button>
        <div class="flex gap-4">
          <button v-if="currentStep > 0"
                  @click="prevStep"
                  class="px-6 py-2 bg-gray-700 rounded-lg hover:bg-gray-600 !rounded-button whitespace-nowrap">
            上一步
          </button>
          <button @click="nextStep"
                  class="px-6 py-2 bg-[#2468F2] rounded-lg hover:bg-blue-600 !rounded-button whitespace-nowrap">
            {{ currentStep === steps.length - 1 ? '完成' : '下一步' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
<script  setup>
import { ref, reactive, defineEmits } from 'vue';
import {get,post} from "@/utils/api";
import config from "@/config";
import {AddIcon, DeleteIcon, LinkIcon} from "tdesign-icons-vue-next";
import {MessagePlugin} from "tdesign-vue-next";
// eslint-disable-next-line vue/no-setup-props-destructure
const { item } = defineProps({
  item: {
    type: Object,
    required: true,
  },
});
if(item!==undefined && item!=null){
  get(config.getTask,{task_id:item.id}).then(res=>{
    let data = res.data.data
    formData.type = data.type;
    formData.taskName = data.title;
    formData.selectedAudioPlatform = data.audio_platform;
    formData.selectedVoice = parseInt(data.voice);
    formData.selectedVoiceModel = data.voice_model
    formData.selectedVideoPlatform = data.video_platform;
    formData.selectedVideo = parseInt(data.video);
    isAutoFb.value = formData.is_auto_fb = data.is_auto_fb === 1
    isAutoJjjb.value = formData.is_auto_jjjb = data.is_auto_jjjb === 1
    isAutoFbjb.value = formData.is_auto_fbjb = data.is_auto_fbjb === 1
    if(data.push_schedule!=null){
      schedule.value = data.push_schedule_arr
    }
    getVoices(data.audio_platform)
    getVideos(data.video_platform)
    if(data.audio_platform=="MINIMAX"){
      platformVoicesModel.value = [
        { label: "快速版V1", value: "speech-01-turbo" },
        { label: "快速版V2", value: "speech-02-turbo" },
        { label: "高保真V1版", value: "speech-01-hd" },
        { label: "高保真V2版", value: "speech-02-hd" },
      ];
    }else{
      platformVoicesModel.value = [];
    }
  })

}
const currentStep = ref(0);
const platformVoices = ref([]);
const platformVideos = ref([]);
const audioPlatforms = ref([
  // { label: 'MINIMAX', value: 'MINIMAX' },
  { label: '标准', value: '蝉镜' },
  { label: '高清(功能努力开发中...)', value: 'MINIMAX' , disabled: true },
]);
const videoPlatforms = ref([
  { label: '标准', value: '小甲鱼' },
  //{ label: '标准', value: '蝉镜' },
  { label: '高清(功能努力开发中...)', value: 'HeyGen', disabled: true },
    // { label: 'HeyGen', value: 'HeyGen' },
]);


//获取声音平台
// const getVoicePlatforms = () => {
//   get(config.getConfigList,{cat:3}).then(res=>{
//     console.log("getVoicePlatforms", res.data.data)
//     let data = res.data.data
//     audioPlatforms.value = []
//     for (let i = 0; i < data.length; i++) {
//       audioPlatforms.value.push({ label:data[i].name, value: data[i].id })
//     }
//   })
// }
// getVoicePlatforms()
const platformVoicesModel = ref([])
//声音平台切换事件
const selectAudioPlatform = (platform,context) => {
  console.log("selectAudioPlatform",platform)
  console.log("context",context)
  getVoices(platform)
  if(context.option.label=="MINIMAX"){
    platformVoicesModel.value = [
      { label: "快速版V1", value: "speech-01-turbo" },
      { label: "快速版V2", value: "speech-02-turbo" },
      { label: "高保真V1版", value: "speech-01-hd" },
      { label: "高保真V2版", value: "speech-02-hd" },
    ];
  }
};




//视频平台切换事件
const selectVideoPlatform = (platform) => {
  console.log("selectVideoPlatform",platform)
  getVideos(platform)
};

//获取对应平台声音模板
const getVoices = (platform) => {
  get(config.getVideoList,{type:1,platform_name:platform}).then(res=>{
    let data = res.data.data
    platformVoices.value = []
    platformVoices.value = [{ label:"根据文案情绪选择", value: 0}]
    for (let i = 0; i < data.length; i++) {
      platformVoices.value.push({ label:data[i].name, value: data[i].id })
    }
  })

}
//获取对应平台视频模板
const getVideos = (platform) => {
  get(config.getVideoList,{type:2,platform_name:platform}).then(res=>{
    console.log("getVideos", res.data.data)
    let data = res.data.data
    platformVideos.value = []
    platformVideos.value = [{ label:"根据文案情绪选择", value: 0}]
    for (let i = 0; i < data.length; i++) {
      platformVideos.value.push({ label:data[i].name, value: data[i].id })
    }
  })

}





const steps = ['文案配置', '音频配置', '视频配置','发布配置'];
const formData = reactive({
  taskName: '',
  defaultValue: '',
  selectedModel: '',
  volume: 50,
  speed: 100,
  selectedAudioPlatform: '',
  selectedVoice: '',
  selectedVideoPlatform: '',
  selectedVideo: '',
  otherConfig: '',
  outCount:'',
  selectedVoiceModel:'',
  textSelect:'1',
  file_path:""

});
const textSelect = ref([
      {
        label: '自动筛选',
        value: '1',
      },
      {
        label: '手动筛选',
        value: '2',
      }
]
)

const errors = reactive({
  taskName: ''
});
const systemVariables = ['{{标题}}', '{{描述}}'];

const insertSystemVariable = (variable) => {
  formData.systemPrompt += variable;
};
const insertUserVariable = (variable) => {
  formData.userPrompt += variable;
};
const validateStep = () => {
  errors.taskName = '';
  if (currentStep.value === 0 && !formData.taskName) {
    errors.taskName = '请输入任务名称';
    return false;
  }

  parseExcelResulet.value.errors = '';
  if (currentStep.value === 0 && !formData.file_path) {
    parseExcelResulet.value.errors = '请上传口播文本表格文件';
    return false;
  }

  errors.selectedAudioPlatform = '';
  if (currentStep.value === 1 && !formData.selectedAudioPlatform) {
    errors.selectedAudioPlatform = '请选择清晰度';
    return false;
  }

  // errors.selectedVoice = '';
  // if (currentStep.value === 1 && !formData.selectedVoice) {
  //   errors.selectedVoice = '请选择声音';
  //   return false;
  // }

  errors.selectedVoiceModel = '';
  if (currentStep.value === 1 && !formData.selectedVoiceModel &&  formData.selectedAudioPlatform==='MINIMAX') {
    errors.selectedVoiceModel = '请选择声音模型';
    return false;
  }

  errors.selectedVideoPlatform = '';
  if (currentStep.value === 2 && !formData.selectedVideoPlatform) {
    errors.selectedVideoPlatform = '请选择清晰度';
    return false;
  }

  // errors.selectedVideo = '';
  // if (currentStep.value === 2 && !formData.selectedVideo) {
  //   errors.selectedVideo = '请选择视频';
  //   return false;
  // }


  return true;
};
const emit = defineEmits(['close']);
const nextStep = () => {
  if (!validateStep()) return;
  if (currentStep.value < steps.length - 1) {
    currentStep.value++;
  } else {
  // 提交表单
    console.log('提交表单', formData);
    formData.type = 2
    formData.schedule = schedule.value;
    if(isAutoJjjb.value || isAutoJjjb.value){
      formData.is_auto_fb = 1;
    }else{
      formData.is_auto_fb = 2;
    }
    //formData.is_auto_fb = isAutoFb.value ? 1: 2;
    formData.is_auto_jjjb = isAutoJjjb.value ? 1: 2;
    formData.is_auto_fbjb = isAutoFbjb.value ? 1: 2;
    post(config.createTaskZdy, formData).then(response => {
      console.log(response);
      if (response.data.code === 1) {
        console.log('提交成功');
        // 关闭弹窗
        emit('close');
      } else {
        MessagePlugin.error(response.data.info)
        console.log('提交失败');
      }
    });
  }
};
const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--;
  }
};

const cancel = () => {
// 取消操作
  console.log('取消')

 // 关闭弹窗
  emit('close');

};

//发布配置相关
const schedule = ref([
    {
      target_device:[],
      schedule_type:2,
      schedule_value:1,
      schedule_time:[{
        time:['09:00:00','10:00:00'],
        push_num:1
      }],
      push_num:1,
      platform:[1]
    }
])
const platforms = ref([
  {
    label: '抖音',
    value: 1,
  },
  {
    label:'小红书',
    value: 2
  },
  {
    label: '微信视频号',
    value: 3,
  }

])



const devices = ref();
const deviceList = async () => {
  console.log("deviceList");
  try {
    const response = await get(config.getDeviceListGroup,{

    }); // Adjust API endpoint as needed
    if (response.status === 200) {
      devices.value  = response.data.data;
      console.log("deviceList",devices.value)
      // data.value = data;
    } else {
      console.error('Failed to fetch feedback data');
    }
  } catch (error) {
    console.error('Error fetching feedback data:', error);
  }


};
deviceList()
const schedule_types = ref([
  {
    label: '间隔发布',
    value: 2,
  },
  {
    label: '每日时段',
    value: 1,
  },
])

//新增时间
const addTime = (key) => {
  schedule.value[key].schedule_time.push({
    time:[],
    push_num:1
  })
}

//删除时间
const removeTime = (key,index) => {
  schedule.value[key].schedule_time.splice(index,1)
}

//新增配置
const addSchedule = () => {
  schedule.value.push({
    target_device:[],
    schedule_type:2,
    schedule_value:'',
    schedule_time:[{
      time:[],
      push_num:1
    }],
    push_num:1
  })
}

//删除配置
const removeSchedule = (key) => {
  schedule.value.splice(key,1)
}

const files = ref([]);

const handleFail = ({ file }) => {
  MessagePlugin.error(`文件 ${file.name} 上传失败`);
};
const parseExcelResulet = ref({
  errors:"",
  success:""
})
const handleSuccess = ( res ) => {
  if(res.response.code===1){
    let loading = MessagePlugin.loading("文件上传成功,正在解析...")
    post(config.parseExcel,{file_url:res.response.data.url}).then(response => {
      MessagePlugin.close(loading)
      console.log("parseExcelResulet",response)
      if(response.data.code===1){
        parseExcelResulet.value.success  = response.data.info
        parseExcelResulet.value.errors = ""
        formData.file_path = res.response.data.url
        console.log("parseExcelResulet222222",parseExcelResulet.value)
       // MessagePlugin.success("文件解析成功")
      }else{
        parseExcelResulet.value.errors  = response.data.info
        parseExcelResulet.value.success = ""
      //  MessagePlugin.error(response.data.info)
      }
    })
  }else{
    MessagePlugin.error(res.response.info)
  }
  console.log("handleSuccess",res)
};
const isAutoFb = ref(false)
const isAutoJjjb = ref(false)
const isAutoFbjb = ref(false)




</script>
<style scoped>
input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 16px;
  height: 16px;
  background: #2468F2;
  border-radius: 50%;
  cursor: pointer;
}
input[type="range"]::-moz-range-thumb {
  width: 16px;
  height: 16px;
  background: #2468F2;
  border-radius: 50%;
  cursor: pointer;
}
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
.bg-gray-800{
  background-color: rgb(50 53 56 / 50%);
}
.bg-gray-700 {
  --tw-bg-opacity: 1;
  background-color: rgb(51 53 54);
}
.bg-blue-900 {
  --tw-bg-opacity: 1;
  background-color: rgb(22 23 26);
}
</style>
